var apiUrl = $("#apiUrl").val();
$(document).ready(function (){
    menuCss("安装");
    $("#filter-hospital").val(null);
    $("#filter-hospital").select2({
        language: 'zh-CN',
        placeholder: '医院',
        allowClear: true});
    $("#queryForm").find("[name='status']").val(null);
    $("#queryForm").find("[name='status']").select2({
        language: 'zh-CN',
        placeholder: '状态',
        allowClear: true});
    $("#queryForm").find("[name='manufacturerId']").val(null);
    $("#queryForm").find("[name='manufacturerId']").select2({
        language: 'zh-CN',
        placeholder: '厂商',
        allowClear: true});
    $("#filter-maintainer").val(null);
    $("#filter-maintainer").select2({
        language: 'zh-CN',
        placeholder: '维修商',
        allowClear: true});

    // 初始化复选框
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    $("select[name='fileType']").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        multiple: true
    });
    initQueryTerm();
    getInstallList();
    $("#show-count").change(function(){
        getInstallList();
    })
    $("[name='is_dispatch']").on("ifChecked",function (){
        var value = $(this).val();
        localIsDispaxth = value;
        if(value == 1){
            $("#dispatchDiv").show();
            engineerNameV = hospitalContactsV = dispathTimeV = notEmptyValid;
            engineerPhoneV = {
                validators: {
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }

            hospitalPhoneV = {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
        }else{
            $("#dispatchDiv").hide();
            engineerNameV = null;
            hospitalContactsV = null;
            dispathTimeV = null;
            engineerPhoneV = null;
            hospitalPhoneV = null;
        }
    });
    $("#assign-model").find("[name='engineerName']").blur(function (){
        engineerNameBlur(this);
    });
});

function installInfo(id){
    location.href="<%=basePath%>/install/info?id="+666;
}

// 分配服务商Model
$("#assign-model").iziModal({
    title: "服务商",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1000,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        $("#assign-maintainer").val(null);
        $("#assign-maintainer").select2({
            language: 'zh-CN',
            placeholder: '服务商',
            allowClear: true
        });
        validator();
        if(localDeviceId != "null"){
            getDeviceInfo(localDeviceId);
        }
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#assignForm')[0].reset();
        $("#assignForm").data('bootstrapValidator').destroy();
    }
});

// 信息补全
$("#improve-model").iziModal({
    title: "信息补全",
    headerColor: '#00c0ef',
    rtl: false,
    width: 650,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator3()
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#improve-form')[0].reset();
        $("#repairMode,#repairDeviceStartStatus,#repairDeviceEndStatus").val("").trigger("change");
        $("#improve-form").data('bootstrapValidator').destroy();
        $('#improve-one')[0].reset();
        $('#improve-two')[0].reset();
        $('#improve-three')[0].reset();
        $('#improve-four')[0].reset();
    }
});

// 确认维修Model
$("#event-model").iziModal({
    title: "添加事件",
    headerColor: '#00c0ef',
    rtl: false,
    width: 650,
    zindex: 1042,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    overlayClose: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: true,
    onOpening: function () {
        validator2();
    },
    onOpened: function () {},
    onClosing: function () {},
    onClosed: function () {
        $('#event-form')[0].reset();
        $("#event-form").data('bootstrapValidator').destroy();
    }
});

function confirm(){
    if($("input[name='one']:checked").length){
        localInstallId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceid");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus == "1205"){//只能是待确认状态下才能确认
            $("#confirmDiv").confirmData({
                keyType:2903,
                keyId: localInstallId,
                root:apiUrl,
                confirmUrl: "install/confirm",
                typeStatus: 3,
                deviceId: localDeviceId,
                callback:function(obj){
                    var isSuccess = obj.returnIsSuccess();
                    if(isSuccess){
                        flavrShowByTime("操作成功",null,"success",null);
                        getInstallList();
                    }else{
                        flavrShowByTime("操作失败",null,"success",null);
                    }
                }
            });
        }else{
            flavrShowByTime("只能是待确认状态下才能确认",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}

// 打开分配服务商的model
var localInstallId,localDeviceId = null,localStatus;
function openAssignModel(){
    if($("input[name='one']:checked").length){
        if(localStatus == "2200"){//只能是待处理状态下才能分配
            $("#assign-model").iziModal("open",this);
        }else{
            flavrShowByTime("只有待处理状态下才能分配",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}
function improveInfo(){
    if($("input[name='one']:checked").length){
        localInstallId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceid");
        contractDeviceActualsendId = $("input[name='one']:checked").attr("contractdeviceactualsendid");
        localStatus = $("input[name='one']:checked").attr("status");
        if(localStatus < "1203"){//2402 已完成验收 则不能在补全信息了
            $("#improve-model").iziModal("open",this);
        }else{
            flavrShowByTime("该安装单已完成，不能在补全信息",null,"danger",null);
        }
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}

function addEvent(){
    if($("input[name='one']:checked").length){
        localInstallId = $("input[name='one']:checked").val();
        localDeviceId = $("input[name='one']:checked").attr("deviceid");
        contractDeviceActualsendId = $("input[name='one']:checked").attr("contractdeviceactualsendid");
        localStatus = $("input[name='one']:checked").attr("status");
        $("#event-model").iziModal("open",this);
        var json = {keyType:1600, keyId: localInstallId,type:"event",root:apiUrl};
        $("#saveEventDiv").eventData(json);
    }else{
        flavrShowByTime("请选择一条维修记录",null,"danger",null);
    }
}

//分配提交
function submitAssign(){
    $('#assignForm').bootstrapValidator('validate');
    if($('#assignForm').data('bootstrapValidator').isValid()){
        var submitData = {
            repairId: localInstallId,
            serviceId: $("#assign-maintainer").val(),
            isDispatch: localIsDispaxth,
            dispatchTime: localIsDispaxth == 1 ? $("#dispathTime").val(): null,
            hospitalContacts: localIsDispaxth == 1 ? $("#hospitalContacts").val() : null,
            hospitalPhone: localIsDispaxth == 1 ? $("#hospitalPhone").val() : null,
            engineerName: localIsDispaxth == 1 ? $("#engineerName").val() : null,//负责人
            engineerPhone: localIsDispaxth == 1 ? $("#engineerPhone").val() : null//负责人电话
        }
        publicAjax(apiUrl+"repair/distribution","POST",submitData,function (data) {
            if(data.ret == 200){
                flavrShowByTime("操作成功",null,"success",null);
                $("#assign-model").iziModal("close");               
            }else{
                flavrShowByTime(data.msg,null,"danger",null);
            }
        })
    }
}

//补全信息提交
var boolImprove = false;
function improveConfirm(){
    $("#improveInstallId,#installIdOne,#installIdTwo,#installIdThree,#installIdFour").val(localInstallId);
    $("#contractDeviceActualSendId").val(contractDeviceActualsendId);
    $("#deviceId").val(localDeviceId);
    $('#improve-form').bootstrapValidator('validate');
    if($('#improve-form').data('bootstrapValidator').isValid()){
        if(!boolImprove){
            boolImprove = true;
            isFileUpload($("#improve-one"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveOneFileIds").val(fileIdStr.join(","));
            })
            isFileUpload($("#improve-two"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveTwoFileIds").val(fileIdStr.join(","));
            })
            isFileUpload($("#improve-three"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveThreeFileIds").val(fileIdStr.join(","));
            })
            isFileUpload($("#improve-four"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#improveFourFileIds").val(fileIdStr.join(","));
            })
            var fildStrs = [];
            if($("#improveOneFileIds").val()){
                fildStrs.push($("#improveOneFileIds").val());
            }
            if($("#improveTwoFileIds").val()){
                fildStrs.push($("#improveTwoFileIds").val());
            }
            if($("#improveThreeFileIds").val()){
                fildStrs.push($("#improveThreeFileIds").val());
            }
            if($("#improveFourFileIds").val()){
                fildStrs.push($("#improveFourFileIds").val());
            }
            $("#improveFileIds").val(fildStrs.join(","));
            var url=apiUrl+"install/saveInstallData";
            publicAjax(url,"POST",$("#improve-form"),function (data){
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    $("#improve-model").iziModal("close",this);
                    getInstallList();
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
                boolImprove =false;
            })
        }
    }
}

//添加事件提交按钮
var boolEvent = false;
function eventConfirm(){
    $("#eventRepairId").val(localInstallId);
    $('#event-form').bootstrapValidator('validate');
    if($('#event-form').data('bootstrapValidator').isValid()){
        if(!boolEvent){
            boolEvent = true;
            isFileUpload($("#event-form"),function (data){
                var fileIdStr = [];
                for(var x=0;x<data.length;x++){
                    fileIdStr.push(data[x].fileId);
                }
                $("#eventFileIds").val(fileIdStr.join(","));
                var url=apiUrl+"/event/addEventForWeChat";
                publicAjax(url,"POST",$("#event-form"),function (data){
                    if(data.ret == 200){
                        flavrShowByTime(data.msg,null,"success",false);
                        $("#event-model").iziModal("close",this);
                        getInstallList();
                    }else{
                        flavrShowByTime(data.msg,null,"danger",false);
                    }
                    boolEvent =false;
                });
            });
            /*var url=apiUrl+"/event/addEvent";
            $.ajax({
                type: "POST",
                url: url,
                data : new FormData($("#event-form")[0]),//整个表单提交
                dataType : "json",
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function(data){
                    if(data.ret == 200){
                        $("#event-model").iziModal("close",this);
                        flavrShowByTime(data.msg,null,"success",false);
                        getInstallList();
                    }else{
                        flavrShowByTime(data.msg,null,"danger");
                    }
                    boolEvent =false;
                },
                failure: function(){
                    flavrShowByTime(data.msg,null,"danger");
                    boolEvent =false;
                }
            })*/
        }
    }
}

function isFileUpload(form,fn){
    var flag = false;
    var url = apiUrl + "fileUpload/fileUploadForWeChat";
    $($(form).find("[name='files']")).each(function (){
        if($(this).val()!= ""){
            flag=true;
        }
    })
    if(flag){
        fileUplod(url,$(form),function (fileList){
                fn(fileList);
        });
    }else{
        fn([]);
    }
}

function initDomCss(){
    $('input.flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
    $("#assignForm").find("input[name='dispathTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#assignForm').data('bootstrapValidator')
            .updateStatus('dispathTime', 'NOT_VALIDATED',null)
            .validateField('dispathTime');
    });

    $("#eventDateTime").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    }).on('hide',function(e) {
        $('#event-form').data('bootstrapValidator')
            .updateStatus('eventDateTime', 'NOT_VALIDATED',null)
            .validateField('eventDateTime');
    });

    $("#start-date,#end-date").datetimepicker({
        autoclose: true,
        todayHighlight:true,
        language:'zh-CN',
        forceParse:true,
        format:'yyyy-mm-dd',
        minView:2,
        todayBtn:true
    })

    $("#actualInstallDate").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    })

    $("#enableTime").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        minuteStep:1,
        todayBtn: true
    })

    $("#improveDepartment").val(null);
    $("#improveDepartment").select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true
    });
}

function initQueryTerm(){
    var url = apiUrl+"/base/queryHosital";
    $("#filter-hospital").html("");
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.hospitalId+"'>"+item.hospitalName+"</option>";
            });

            $("#queryForm select[name='hospitalId']").html(html);
            $("#queryForm select[name='hospitalId']").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = apiUrl + "/base/queryManufacturer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.manufacturerId+"'>"+item.manufacturerName+"</option>";
            });
            $("#filter-manufacturer").html(html);
            $("#filter-manufacturer").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    url = apiUrl + "/base/queryMaintainer";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.maintainerId+"'>"+item.maintainerName+"</option>";
            });
            $("#filter-maintainer,#assign-maintainer").html(html);
            $("#filter-maintainer,#assign-maintainer").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });

    $("#filter-status").html("");
    url = apiUrl + "/base/queryItem";
    publicAjax(url,"POST",{type:'install_status'},function (data) {
        if(data.ret == 200){
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.itemId+"'>"+item.item+"</option>";
            });
            $("#filter-status").html(html);
            $("#filter-status").val(null);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function refresh(){
    window.location.reload();
}

function search(){
    getInstallList();
}

function getInstallList(){
    $("#install_table").html("");
    filterData = {
        start: 0,
        end: $("#show-count").val(),
        contractNo: $("#filter-contract-no").val(),
        deviceName: $("#assets-name").val(),
        firstPartyName: $("#first-party-name").val(),
        secondPartyName: $("#second-party-name").val(),
        startDate: $("#start-date").val(),
        endDate: $("#end-date").val(),
        status: $("#filter-status").val()
    }
    publicAjax(apiUrl+"install/installListForWeb","POST",filterData,function (data) {
        if(data.ret == 200){
            $("#total-count").text(data.data.count);
            if(data.data.count){
                $.each(data.data.data, function(index, item){
                    $("#install_table").append("<tr>\
                        <td>"+(index+1)+"</td>\
                        <td class='text-center text-muted'>\
                            <input type='checkbox' class='flat-green' deviceid='"+item.deviceId+"' contractdeviceactualsendid='"+item.contractDeviceActualSendId+"' status='"+item.status+"' name='one' value='"+item.installId+"'>\
                        </td>\
                        <td class='text-center text-muted'><button type='button' class='btn btn-primary btn-xs' onclick='queryInstallInfo("+item.installId+")' data-original-title='详情'><i class='fa fa-file-text-o'></i></button></td>\
                        <td class='text-muted'>"+(item.deviceName || '')+"</td>\
                        <td class='text-muted'>"+(item.hospitalContacts || '')+"</td>\
                        <td class='text-muted'>"+(item.hospitalPhone || '')+"</td>\
                        <td class='text-muted'>"+(item.projectChargePerson || '')+"</td>\
                        <td class='text-muted'>"+(item.estimateInstallDate || '')+"</td>\
                        <td class='text-muted'>"+(item.statusItem || '')+"</td>\
                        <td class='text-muted'>"+(item.contractNo || '')+"</td>\
                        <td class='text-muted'>"+(item.serviceName || '')+"</td>\
                        <td class='text-muted'>"+(item.commentStatusName || '')+"</td>\
                    </tr>")
                })
                initDomCss();
            }else{
                $("#install_table").html("<tr><td class='text-center text-muted' colspan='15'>暂无安装记录</td></tr>");
            }
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

var assignMaintainerV,engineerNameV,hospitalContactsV,dispathTimeV,engineerPhoneV,hospitalPhoneV;
var notEmptyValid = {
    validators: {
        notEmpty: {
            message: '不能为空'
        }
    }
}
assignMaintainerV = engineerNameV = hospitalContactsV = dispathTimeV = notEmptyValid;
engineerPhoneV = {
    validators: {
        regexp: {
            regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: '请填写正确的手机号码'
        }
    }
}

hospitalPhoneV = {
    validators: {
        notEmpty: {
            message: '不能为空'
        },
        regexp: {
            regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: '请填写正确的手机号码'
        }
    }
}
//分配表单校验
function validator(){
    $('#assignForm').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            assignMaintainer: assignMaintainerV,
            engineerName: engineerNameV,
            hospitalContacts: hospitalContactsV,
            engineerPhone: engineerPhoneV,
            hospitalPhone: hospitalPhoneV,
            dispathTime: dispathTimeV
        }
    });
}
//添加时间表单校验
function validator2(){
    $('#event-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            eventTitle: notEmptyValid,
            eventDateTime: notEmptyValid,
            eventContent: notEmptyValid
        }
    });
}

//信息补全校验
function validator3(){
    $('#improve-form').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            repairDeviceEndStatus: notEmptyValid,
            travelTime: {
                validators: {
                    regexp: {
                        regexp: /^\d+(?:\.\d{1,2})?$/,
                        message: '只能输入数字，且最多保留两位小数'
                    }
                }
            }
        }
    });
}

$('input[name=files]').fileinput({
    language: 'zh', //设置语言
    enctype: 'multipart/form-data',
    showUpload: false, //是否显示上传按钮
    showCaption: false,//是否显示标题
    browseClass: "btn btn-info", //按钮样式
    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
});

//获取设备信息
function getDeviceInfo(id){
    publicAjax(apiUrl+"base/queryManufacturerByDeviceId","POST",{deviceId: id},function (data) {
        if(data.ret == 200){
            $("#deviceNameSpan").html(data.data.deviceName || '');
            $("#deviceModelSpan").html(data.data.deviceModel || '');
            $("#snSpan").html(data.data.sn || '');
            $("#lastUpkeepDateSpan").html(data.data.lastUpkeepDate || '');
            $("#manufacturerNameSpan").html(data.data.manufacturerName || '');
            $("#manufacturerContactsSpan").html(data.data.manufacturerContacts || '');//厂商联系人
            $("#manufacturerPhoneSpan").html(data.data.manufacturerPhone || '');
            $("#InsideOutsideStrSpan").html(data.data.guaranteeStatus || '');
            $("#maintainerNameSpan").html(data.data.maintainerName ||'');
            $("#maintainerContactsSpan").html(data.data.maintainerContacts ||'');
            $("#maintainerPhoneSpan").html(data.data.maintainerPhone ||'');
            $("#endGuaranteeDateSpan").html(data.data.endDate);
        }
    })
}

function queryInstallInfo(id){
    location.href = apiUrl+"install/info?id="+id;
}
